package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.util.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Ricky
 * @date 2021/4/29
 */
public class AddDate extends BaseFn {
    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String dateStr = String.valueOf(arguments[0]);
        int num = Integer.parseInt(String.valueOf(arguments[1]));

        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        Matcher matcher = DATE_PATTERN.matcher(dateStr);
        if (!matcher.find()) {
            throw new AppException("dateStr：" + dateStr + "日期格式不满足2000-01-01的格式");
        }
        dateStr = matcher.group(1);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.parse(dateStr + " 00:00:00"));
        calendar.add(Calendar.DATE, num);
        return DateUtil.format(calendar.getTime());
    }

    @Override
    public String getZwmc() {
        return "日期加减法";
    }

    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("dateStr"));
        params.add(new Param("param2", "整数"));
        return params;
    }

    @Override
    public String getName() {
        return "addDate";
    }
}
